﻿using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace OpenApiHostService
{
	static class Program
	{
		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		static void Main(params string[] args)
		{
			if (args.Length == 0)
			{
				RunServices();
			}
			else
			{
				RunCommands(args);
			}
		}

		/// <summary>
		/// 运行服务
		/// </summary>
		static void RunServices()
		{
			ServiceBase[] ServicesToRun;
			ServicesToRun = new ServiceBase[] 
            { 
				new MyService()
            };
			ServiceBase.Run(ServicesToRun);
		}

		/// <summary>
		/// 运行命令
		/// </summary>
		/// <param name="args"></param>
		static void RunCommands(string[] args)
		{
            ProjectInstaller installer = GetInstaller();
			String argCommand = args[0].ToLower();

            if (args.Length > 1)
            {
                String argServiceName = args[1];
                if (!String.IsNullOrWhiteSpace(argServiceName))
                {
                    installer.MyServiceInstaller.ServiceName = argServiceName;
                    installer.MyServiceInstaller.DisplayName += "(" + argServiceName + ")";
                }
            }

			if (argCommand == "/install" || argCommand == "/i")	// 安装服务
			{
				Dictionary<Object, Object> stateSaver = new Dictionary<Object, Object>();
				installer.Install(stateSaver);
				foreach (var kv in stateSaver)
				{
					Print(stateSaver, 0);
				}
			}
			else if (argCommand == "/uninstall" || argCommand == "/u") // 卸载服务
			{
				installer.Uninstall(null);

			}
			else if (argCommand == "/start" || argCommand == "/s") // 启动服务
			{
				try
				{
					ServiceController sc = new ServiceController(installer.MyServiceInstaller.ServiceName);
					if (sc.Status == ServiceControllerStatus.Stopped)
					{
						sc.Start();
						Console.WriteLine("服务启动成功。");
					}
					else
					{
						Console.WriteLine("已经启动或无法启动。");
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
			}
			else if (argCommand == "/stop")
			{
				try
				{
					ServiceController sc = new ServiceController(installer.MyServiceInstaller.ServiceName);
					if (sc.Status == ServiceControllerStatus.Running)
					{
						sc.Stop();
						Console.WriteLine("服务停止成功。");
					}
					else
					{
						Console.WriteLine("已经停止或无法停止。");
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
			}
			else if (argCommand == "/console" || argCommand == "/c")
			{
				(new MyService()).Start();
				Console.WriteLine("按Enter结束...");
				Console.ReadLine();
			}
			else
			{
				Console.WriteLine("参数不正确：" + argCommand);
			}
		}

		static ProjectInstaller GetInstaller()
		{
			ProjectInstaller installer = new ProjectInstaller();
			installer.BeforeInstall += new InstallEventHandler((obj, state) => { Console.WriteLine("服务正在安装......"); });
			installer.AfterInstall += new InstallEventHandler((obj, state) => { Console.WriteLine("服务安装完成！"); });
			installer.BeforeUninstall += new InstallEventHandler((obj, state) => { Console.WriteLine("服务正在卸载......"); });
			installer.AfterUninstall += new InstallEventHandler((obj, state) => { Console.WriteLine("服务卸载完成！"); });


			string logFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "installer.log");
			string path = string.Format("/assemblypath={0}", System.Reflection.Assembly.GetExecutingAssembly().Location);
			string[] cmd = { path };
			InstallContext context = new InstallContext(logFile, cmd);
			installer.Context = context;

			return installer;
		}

		static void Print(IDictionary<Object, Object> stateSaver, int tabIndent)
		{
			foreach (var kv in stateSaver)
			{
				if (kv.Value is IDictionary<Object, Object> && tabIndent < 5)
				{
					Print(kv.Value as IDictionary<Object, Object>, tabIndent + 1);
				}
				else
				{
					var tabs = "";
					while (tabIndent-- > 0)
					{
						tabs += "\t";
					}
					Console.WriteLine(tabs + kv.Key + "===" + kv.Value);
				}
			}
		}
	}
}
